import QtQuick
import QtQuick.Controls
import QtQuick3D

Rectangle {
    id: earthDetail3DPage
    anchors.fill: parent
    color: "#0a0a1e"
    
    signal closeRequested()
    
    // 计算晨昏线
    QtObject {
        id: sunCalculator
        
        function calculateEarthRotation() {
            var now = new Date()
            var utcHours = now.getUTCHours()
            var utcMinutes = now.getUTCMinutes()
            var utcSeconds = now.getUTCSeconds()
            var totalHours = utcHours + utcMinutes / 60.0 + utcSeconds / 3600.0
            return -(totalHours * 15.0)  // 转换为角度
        }
        
        function calculateSolarDeclination() {
            var now = new Date()
            var startOfYear = new Date(now.getFullYear(), 0, 1)
            var dayOfYear = Math.floor((now - startOfYear) / (24 * 60 * 60 * 1000)) + 1
            return -23.44 * Math.cos((360.0 / 365.0) * (dayOfYear + 10) * Math.PI / 180.0)
        }
        
        function beijingTimeString() {
            var now = new Date()
            var bj = new Date(now.getTime() + 8 * 60 * 60 * 1000)
            var h = bj.getUTCHours().toString().padStart(2, '0')
            var m = bj.getUTCMinutes().toString().padStart(2, '0')
            var s = bj.getUTCSeconds().toString().padStart(2, '0')
            return h + ":" + m + ":" + s
        }
    }
    
    // 左侧信息面板
    Rectangle {
        id: infoPanel
        anchors.left: parent.left
        anchors.top: parent.top
        anchors.bottom: parent.bottom
        width: 380
        color: "#1a1a2e"
        border.color: "#4ECDC4"
        border.width: 2
        z: 100
        
        Flickable {
            anchors.fill: parent
            anchors.margins: 20
            contentHeight: infoColumn.height
            clip: true
            
            Column {
                id: infoColumn
                width: parent.width
                spacing: 15
                
                Text {
                    text: "🌍 地球详细视图"
                    font.pixelSize: 26
                    font.bold: true
                    color: "#4ECDC4"
                }
                
                Rectangle {
                    width: parent.width - 20
                    height: 2
                    color: "#4ECDC440"
                }
                
                Column {
                    width: parent.width
                    spacing: 12
                    
                    Repeater {
                        model: [
                            {label: "英文名", value: "Earth"},
                            {label: "半径", value: "6,371 km"},
                            {label: "质量", value: "5.97 × 10²⁴ kg"},
                            {label: "距太阳距离", value: "1.00 AU"},
                            {label: "公转周期", value: "365.25 天"},
                            {label: "自转周期", value: "1.00 天 (24小时)"},
                            {label: "地轴倾角", value: "23.5° (黄赤交角)"},
                            {label: "大气成分", value: "78% N₂, 21% O₂"},
                            {label: "表面温度", value: "-88°C ~ 58°C"}
                        ]
                        
                        Row {
                            width: parent.width
                            spacing: 10
                            Text {
                                text: modelData.label + ":"
                                color: "#AAAAAA"
                                font.pixelSize: 14
                                width: 110
                            }
                            Text {
                                text: modelData.value
                                color: "white"
                                font.pixelSize: 14
                                font.bold: true
                            }
                        }
                    }
                }
                
                Item { height: 10 }
                
                Rectangle {
                    width: parent.width
                    height: 90
                    color: "#1a237e40"
                    border.color: "#FFD700"
                    border.width: 1
                    radius: 8
                    
                    Column {
                        anchors.centerIn: parent
                        spacing: 8
                        
                        Text {
                            text: "⏰ 当前时刻晨昏线"
                            font.pixelSize: 14
                            font.bold: true
                            color: "#FFD700"
                            anchors.horizontalCenter: parent.horizontalCenter
                        }
                        
                        Text {
                            id: currentTimeText
                            text: "北京时间: " + sunCalculator.beijingTimeString()
                            font.pixelSize: 13
                            color: "#FFF"
                            anchors.horizontalCenter: parent.horizontalCenter
                        }
                        
                        Text {
                            text: "太阳赤纬: " + sunCalculator.calculateSolarDeclination().toFixed(2) + "°"
                            font.pixelSize: 12
                            color: "#AAA"
                            anchors.horizontalCenter: parent.horizontalCenter
                        }
                    }
                }
                
                Item { height: 5 }
                
                Rectangle {
                    width: parent.width
                    height: 200
                    color: "#2E7D3240"
                    border.color: "#4CAF50"
                    border.width: 1
                    radius: 8
                    
                    Column {
                        anchors.centerIn: parent
                        spacing: 8
                        
                        Text {
                            text: "💡 可视化元素说明"
                            font.pixelSize: 14
                            font.bold: true
                            color: "#4CAF50"
                            anchors.horizontalCenter: parent.horizontalCenter
                        }
                        
                        Text {
                            text: "• 地球沿自转轴持续旋转（60秒/圈）"
                            font.pixelSize: 12
                            color: "#4CAF50"
                        }
                        
                        Text {
                            text: "• 拖动鼠标上下左右改变观察视角"
                            font.pixelSize: 12
                            color: "#4CAF50"
                        }
                        
                        Text {
                            text: "• 滚动鼠标滚轮进行放大和缩小"
                            font.pixelSize: 12
                            color: "#4CAF50"
                        }
                        
                        Text {
                            text: "• 点击右上角🔄按钮重置视角"
                            font.pixelSize: 12
                            color: "#4ECDC4"
                        }
                        
                        Text {
                            text: "• 白色轴线：地球自转轴（23.5°倾角）"
                            font.pixelSize: 12
                            color: "#FFFFFF"
                        }
                        
                        Text {
                            text: "• 红球=北极点 · 蓝球=南极点"
                            font.pixelSize: 12
                            color: "#FFA500"
                        }
                        
                        Text {
                            text: "• 金色网格：黄道平面（公转轨道面）"
                            font.pixelSize: 12
                            color: "#FFD700"
                        }
                        
                        Text {
                            text: "• 光线从左侧照射，右侧为夜晚"
                            font.pixelSize: 12
                            color: "#4CAF50"
                        }
                    }
                }
                
                Item { height: 20 }
                
                Button {
                    anchors.horizontalCenter: parent.horizontalCenter
                    width: 120
                    height: 45
                    
                    background: Rectangle {
                        color: parent.pressed ? "#FF6B6B" : "#FF8E8E"
                        radius: 22
                        border.color: "#FFF"
                        border.width: 2
                    }
                    
                    contentItem: Text {
                        text: "关闭"
                        color: "white"
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                        font.pixelSize: 16
                        font.bold: true
                    }
                    
                    onClicked: earthDetail3DPage.closeRequested()
                }
            }
        }
    }
    
    // 右侧 3D 地球显示区域
    Rectangle {
        anchors.left: infoPanel.right
        anchors.right: parent.right
        anchors.top: parent.top
        anchors.bottom: parent.bottom
        color: "#0a0a1e"
        
        View3D {
            id: view3D
            anchors.fill: parent
            
            // 设置环境和背景
            environment: SceneEnvironment {
                clearColor: "#0a0a1e"
                backgroundMode: SceneEnvironment.Color
                antialiasingMode: SceneEnvironment.MSAA
                antialiasingQuality: SceneEnvironment.High
            }
            
            // 摄像机
            Node {
                id: cameraNode
                position: Qt.vector3d(0, 0, 0)  // 围绕原点旋转
                
                property real rotationX: -15  // 上下旋转角度
                property real rotationY: 0    // 左右旋转角度
                property real cameraDistance: 600  // 摄像机距离（可缩放）
                
                eulerRotation.x: rotationX
                eulerRotation.y: rotationY
                
                PerspectiveCamera {
                    id: camera
                    position: Qt.vector3d(0, 0, cameraNode.cameraDistance)  // 距离可变，引用父节点的属性
                    fieldOfView: 45
                }
            }
            
            // 主光源（模拟太阳光）
            DirectionalLight {
                id: sunLight
                color: "#FFFFFF"
                brightness: 1.2
                eulerRotation.y: 90  // 从左侧照射
                castsShadow: false
            }
            
            // 环境光（较弱，使晨昏线更明显）
            DirectionalLight {
                color: "#202020"
                brightness: 0.15
                eulerRotation.y: -90
            }
            
            // 地球倾斜容器（先设置倾角）
            Node {
                id: earthTiltNode
                eulerRotation.x: 23.5  // 地球倾角23.5度
                
                // 地球自转容器（绕倾斜后的Y轴旋转）
                Node {
                    id: earthNode
                    
                    property real autoRotationY: sunCalculator.calculateEarthRotation()
                    property real animationRotationY: 0  // 持续动画旋转
                    
                    eulerRotation.y: autoRotationY + animationRotationY
                    
                    // 持续自转动画
                    NumberAnimation on animationRotationY {
                        from: 0
                        to: 360
                        duration: 60000  // 60秒转一圈
                        loops: Animation.Infinite
                        running: true
                    }
                    
                    // 地球球体
                Model {
                    id: earthModel
                    source: "#Sphere"
                    scale: Qt.vector3d(2.0, 2.0, 2.0)
                    
                    materials: [
                        PrincipledMaterial {
                            id: earthMaterial
                            baseColorMap: Texture {
                                source: "qrc:/images/earth_day.jpg"
                                generateMipmaps: true
                                mipFilter: Texture.Linear
                            }
                            roughness: 0.8
                            metalness: 0.0
                            
                            // 使用法线贴图增强细节（如果有的话）
                            normalMap: Texture {
                                source: "qrc:/images/earth_day.jpg"  // 这里可以替换为法线贴图
                                generateMipmaps: true
                            }
                        }
                    ]
                }
                
                // 云层（可选，增加真实感）
                // 如果 earth_clouds.png 文件不存在，纹理会自动使用透明色，不影响显示
                Model {
                    id: cloudsModel
                    source: "#Sphere"
                    scale: Qt.vector3d(2.05, 2.05, 2.05)
                    
                    property real cloudRotation: 0
                    
                    // 云层独立旋转（比地球稍快）
                    eulerRotation.y: cloudRotation
                    
                    // 云层持续旋转动画
                    NumberAnimation on cloudRotation {
                        from: 0
                        to: 360
                        duration: 55000  // 55秒转一圈，比地球稍快
                        loops: Animation.Infinite
                        running: true
                    }
                    
                    materials: [
                        PrincipledMaterial {
                            baseColorMap: Texture {
                                source: "qrc:/images/earth_clouds.png"
                                generateMipmaps: true
                            }
                            alphaMode: PrincipledMaterial.Blend
                            opacity: 0.3
                            roughness: 0.9
                            metalness: 0.0
                        }
                    ]
                }
                
                // 地球自转轴（南北极轴线）- 白色实线
                Model {
                    source: "#Cylinder"
                    scale: Qt.vector3d(0.04, 3.5, 0.04)  // 细长的轴
                    position: Qt.vector3d(0, 0, 0)
                    
                    materials: [
                        PrincipledMaterial {
                            baseColor: "#FFFFFF"  // 白色
                            lighting: PrincipledMaterial.NoLighting
                            opacity: 1.0
                        }
                    ]
                }
                
                // 北极点标注
                Model {
                    source: "#Sphere"
                    scale: Qt.vector3d(0.15, 0.15, 0.15)
                    position: Qt.vector3d(0, 1.85, 0)
                    
                    materials: [
                        PrincipledMaterial {
                            baseColor: "#FF0000"  // 红色
                            lighting: PrincipledMaterial.NoLighting
                        }
                    ]
                }
                
                // 南极点标注
                Model {
                    source: "#Sphere"
                    scale: Qt.vector3d(0.15, 0.15, 0.15)
                    position: Qt.vector3d(0, -1.85, 0)
                    
                    materials: [
                        PrincipledMaterial {
                            baseColor: "#0000FF"  // 蓝色
                            lighting: PrincipledMaterial.NoLighting
                        }
                    ]
                }
                }  // earthNode 结束
            }  // earthTiltNode 结束
            
            // 黄道平面 - 黄色网格线平面
            Node {
                id: eclipticPlaneGrid
                position: Qt.vector3d(0, 0, 0)
                
                // 放射状网格线（12条，从球心向外辐射）
                Model {
                    source: "#Cube"
                    scale: Qt.vector3d(9.0, 0.003, 0.025)
                    eulerRotation.y: 0
                    materials: [ PrincipledMaterial { baseColor: "#FFD700"; lighting: PrincipledMaterial.NoLighting; opacity: 0.6; alphaMode: PrincipledMaterial.Blend } ]
                }
                Model {
                    source: "#Cube"
                    scale: Qt.vector3d(9.0, 0.003, 0.025)
                    eulerRotation.y: 30
                    materials: [ PrincipledMaterial { baseColor: "#FFD700"; lighting: PrincipledMaterial.NoLighting; opacity: 0.6; alphaMode: PrincipledMaterial.Blend } ]
                }
                Model {
                    source: "#Cube"
                    scale: Qt.vector3d(9.0, 0.003, 0.025)
                    eulerRotation.y: 60
                    materials: [ PrincipledMaterial { baseColor: "#FFD700"; lighting: PrincipledMaterial.NoLighting; opacity: 0.6; alphaMode: PrincipledMaterial.Blend } ]
                }
                Model {
                    source: "#Cube"
                    scale: Qt.vector3d(9.0, 0.003, 0.025)
                    eulerRotation.y: 90
                    materials: [ PrincipledMaterial { baseColor: "#FFD700"; lighting: PrincipledMaterial.NoLighting; opacity: 0.6; alphaMode: PrincipledMaterial.Blend } ]
                }
                Model {
                    source: "#Cube"
                    scale: Qt.vector3d(9.0, 0.003, 0.025)
                    eulerRotation.y: 120
                    materials: [ PrincipledMaterial { baseColor: "#FFD700"; lighting: PrincipledMaterial.NoLighting; opacity: 0.6; alphaMode: PrincipledMaterial.Blend } ]
                }
                Model {
                    source: "#Cube"
                    scale: Qt.vector3d(9.0, 0.003, 0.025)
                    eulerRotation.y: 150
                    materials: [ PrincipledMaterial { baseColor: "#FFD700"; lighting: PrincipledMaterial.NoLighting; opacity: 0.6; alphaMode: PrincipledMaterial.Blend } ]
                }
                Model {
                    source: "#Cube"
                    scale: Qt.vector3d(9.0, 0.003, 0.025)
                    eulerRotation.y: 180
                    materials: [ PrincipledMaterial { baseColor: "#FFD700"; lighting: PrincipledMaterial.NoLighting; opacity: 0.6; alphaMode: PrincipledMaterial.Blend } ]
                }
                Model {
                    source: "#Cube"
                    scale: Qt.vector3d(9.0, 0.003, 0.025)
                    eulerRotation.y: 210
                    materials: [ PrincipledMaterial { baseColor: "#FFD700"; lighting: PrincipledMaterial.NoLighting; opacity: 0.6; alphaMode: PrincipledMaterial.Blend } ]
                }
                Model {
                    source: "#Cube"
                    scale: Qt.vector3d(9.0, 0.003, 0.025)
                    eulerRotation.y: 240
                    materials: [ PrincipledMaterial { baseColor: "#FFD700"; lighting: PrincipledMaterial.NoLighting; opacity: 0.6; alphaMode: PrincipledMaterial.Blend } ]
                }
                Model {
                    source: "#Cube"
                    scale: Qt.vector3d(9.0, 0.003, 0.025)
                    eulerRotation.y: 270
                    materials: [ PrincipledMaterial { baseColor: "#FFD700"; lighting: PrincipledMaterial.NoLighting; opacity: 0.6; alphaMode: PrincipledMaterial.Blend } ]
                }
                Model {
                    source: "#Cube"
                    scale: Qt.vector3d(9.0, 0.003, 0.025)
                    eulerRotation.y: 300
                    materials: [ PrincipledMaterial { baseColor: "#FFD700"; lighting: PrincipledMaterial.NoLighting; opacity: 0.6; alphaMode: PrincipledMaterial.Blend } ]
                }
                Model {
                    source: "#Cube"
                    scale: Qt.vector3d(9.0, 0.003, 0.025)
                    eulerRotation.y: 330
                    materials: [ PrincipledMaterial { baseColor: "#FFD700"; lighting: PrincipledMaterial.NoLighting; opacity: 0.6; alphaMode: PrincipledMaterial.Blend } ]
                }
                
                // 同心圆网格线 - 细圆环（完全透明中间）
                // 圆环1（半径1.5）
                Model {
                    source: "#Cylinder"
                    scale: Qt.vector3d(1.5, 0.004, 1.5)
                    materials: [
                        PrincipledMaterial {
                            baseColor: "#FFD700"
                            lighting: PrincipledMaterial.NoLighting
                            opacity: 0.7
                            alphaMode: PrincipledMaterial.Blend
                        }
                    ]
                    
                    Model {
                        source: "#Cylinder"
                        scale: Qt.vector3d(0.955, 3.0, 0.955)
                        materials: [
                            PrincipledMaterial {
                                baseColor: "transparent"
                                opacity: 0.0
                                alphaMode: PrincipledMaterial.Blend
                            }
                        ]
                    }
                }
                
                // 圆环2（半径2.5）
                Model {
                    source: "#Cylinder"
                    scale: Qt.vector3d(2.5, 0.004, 2.5)
                    materials: [
                        PrincipledMaterial {
                            baseColor: "#FFD700"
                            lighting: PrincipledMaterial.NoLighting
                            opacity: 0.7
                            alphaMode: PrincipledMaterial.Blend
                        }
                    ]
                    
                    Model {
                        source: "#Cylinder"
                        scale: Qt.vector3d(0.97, 3.0, 0.97)
                        materials: [
                            PrincipledMaterial {
                                baseColor: "transparent"
                                opacity: 0.0
                                alphaMode: PrincipledMaterial.Blend
                            }
                        ]
                    }
                }
                
                // 圆环3（半径3.5）
                Model {
                    source: "#Cylinder"
                    scale: Qt.vector3d(3.5, 0.004, 3.5)
                    materials: [
                        PrincipledMaterial {
                            baseColor: "#FFD700"
                            lighting: PrincipledMaterial.NoLighting
                            opacity: 0.7
                            alphaMode: PrincipledMaterial.Blend
                        }
                    ]
                    
                    Model {
                        source: "#Cylinder"
                        scale: Qt.vector3d(0.975, 3.0, 0.975)
                        materials: [
                            PrincipledMaterial {
                                baseColor: "transparent"
                                opacity: 0.0
                                alphaMode: PrincipledMaterial.Blend
                            }
                        ]
                    }
                }
                
                // 圆环4（半径4.5）
                Model {
                    source: "#Cylinder"
                    scale: Qt.vector3d(4.5, 0.004, 4.5)
                    materials: [
                        PrincipledMaterial {
                            baseColor: "#FFD700"
                            lighting: PrincipledMaterial.NoLighting
                            opacity: 0.7
                            alphaMode: PrincipledMaterial.Blend
                        }
                    ]
                    
                    Model {
                        source: "#Cylinder"
                        scale: Qt.vector3d(0.98, 3.0, 0.98)
                        materials: [
                            PrincipledMaterial {
                                baseColor: "transparent"
                                opacity: 0.0
                                alphaMode: PrincipledMaterial.Blend
                            }
                        ]
                    }
                }
            }  // eclipticPlaneGrid 结束
            
            // 鼠标交互控制 - 控制相机视角和缩放
            MouseArea {
                anchors.fill: parent
                
                property real lastX: 0
                property real lastY: 0
                property bool isDragging: false
                
                onPressed: function(mouse) {
                    lastX = mouse.x
                    lastY = mouse.y
                    isDragging = true
                    cursorShape = Qt.ClosedHandCursor
                }
                
                onReleased: {
                    isDragging = false
                    cursorShape = Qt.OpenHandCursor
                }
                
                onPositionChanged: function(mouse) {
                    if (isDragging) {
                        var deltaX = mouse.x - lastX
                        var deltaY = mouse.y - lastY
                        
                        // 左右拖动改变水平旋转
                        cameraNode.rotationY += deltaX * 0.3
                        
                        // 上下拖动改变垂直旋转
                        cameraNode.rotationX += deltaY * 0.3
                        
                        // 限制垂直旋转角度，避免翻转
                        if (cameraNode.rotationX > 80) cameraNode.rotationX = 80
                        if (cameraNode.rotationX < -80) cameraNode.rotationX = -80
                        
                        lastX = mouse.x
                        lastY = mouse.y
                    }
                }
                
                // 鼠标滚轮缩放
                onWheel: function(wheel) {
                    var delta = wheel.angleDelta.y
                    var zoomSpeed = 30  // 缩放速度
                    
                    // 向上滚动缩小距离（放大），向下滚动增大距离（缩小）
                    cameraNode.cameraDistance -= delta / 120 * zoomSpeed
                    
                    // 限制缩放范围
                    if (cameraNode.cameraDistance < 300) cameraNode.cameraDistance = 300  // 最近距离
                    if (cameraNode.cameraDistance > 1200) cameraNode.cameraDistance = 1200  // 最远距离
                }
                
                cursorShape: Qt.OpenHandCursor
            }
        }
        
        // 重置按钮
        Button {
            anchors.top: parent.top
            anchors.right: parent.right
            anchors.topMargin: 20
            anchors.rightMargin: 20
            width: 100
            height: 40
            z: 200
            
            background: Rectangle {
                color: parent.pressed ? "#4ECDC4" : (parent.hovered ? "#45b8b0" : "#3da9a1")
                radius: 20
                border.color: "#FFF"
                border.width: 2
                opacity: 0.9
            }
            
            contentItem: Row {
                spacing: 5
                anchors.centerIn: parent
                Text {
                    text: "🔄"
                    font.pixelSize: 16
                    color: "white"
                    anchors.verticalCenter: parent.verticalCenter
                }
                Text {
                    text: "重置"
                    color: "white"
                    font.pixelSize: 14
                    font.bold: true
                    anchors.verticalCenter: parent.verticalCenter
                }
            }
            
            onClicked: {
                // 重置摄像机视角和距离到初始值
                cameraNode.rotationX = -15
                cameraNode.rotationY = 0
                cameraNode.cameraDistance = 600
            }
        }
        
        // 说明文字
        Text {
            anchors.bottom: parent.bottom
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.bottomMargin: 30
            text: "地球持续自转 · 拖动旋转视角 · 滚轮缩放 · 白轴=自转轴 · 红=北极 · 蓝=南极 · 金色网格=黄道平面 · 倾角23.5°"
            font.pixelSize: 14
            color: "#888888"
        }
    }
    
    Component.onCompleted: {
        console.log("=== 地球3D视图已创建 ===")
        console.log("使用Qt Quick 3D渲染地球，实时晨昏线")
    }
    
    // 定时更新地球自转和时间显示（根据当前时间）
    Timer {
        interval: 1000
        running: true
        repeat: true
        onTriggered: {
            // 更新时间文本
            currentTimeText.text = "北京时间: " + sunCalculator.beijingTimeString()
            // 更新地球自转角度
            earthNode.autoRotationY = sunCalculator.calculateEarthRotation()
        }
    }
}
